<?php

namespace App\Http\Controllers\Home\User;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Home\Position as PositionModel;
use App\Models\Home\Part;
use Position;
use PositionClass;
use Resume;
use Deliver;
use Client;
use Frame;
use Tools;
use Auth;
use Illuminate\Support\Facades\DB;

class PositionController extends Controller
{
    protected $passField = [
        'time','assign','client_id','emergency','title','region','range','hc','demand'/*,'category'*/,'status','state','reward'
    ];

    public function self(Request $request)
    {
        $in  = [];
        $opt = [];
        $act = [];
        if ( !empty($request->input('title')) ){

            $opt['title'] =['like','%'.$request->input('title').'%'] ;

        }
        if ( !empty($request->input('client_id')) ){

            $opt['client_id'] = $request->input('client_id');

        }

        $act['title'] =  $request->input('title')??'';

        $act['client_id'] =  $request->input('client_id')??'';


        if (!Auth::user()->hasRole('admin') && Auth::user()->type==1){

            $user = Auth::user()->load('frame');

            $member = Frame::getMember($user->frame->id);

            $member[] = Auth::id();

            $in = ['assign',$member];

        }else{

            $part = Part::where('create_uid',Auth::id())->first();

            if ($part && $part->assign && $part->share != 1){

                $in = ['assign',[$part->assign]];

            }else{

                $in = ['assign',[Auth::id()]];
            }


        }

        if(Auth::user()->type==1){
            # 如果上级是管理组就拥有上级和兄弟查看权限-组员
            $belong  = json_decode(Db::table('frame')->where(['uid'=>Auth::id()])->get(),true);
        }else{
            # 如果上级是管理组就拥有上级和兄弟查看权限-兼职
            $borther = json_decode(Db::table('frame')->where(['belong'=>$part->assign])->select('uid')->get(),true);

            foreach($borther as $k=>$v){
                $borther2[] = $v['uid'];
            }

            @array_push($borther2,$part->assign);

            if($borther2){
                $in = [
                    'assign',$borther2
                ];
            }
        }

        if(@$belong[0]['level']==3 && @$belong[0]['belong']!=0 ){

            $borther = json_decode(Db::table('frame')->where(['belong'=>$belong[0]['belong']])->select('uid')->get(),true);

            foreach($borther as $k=>$v){
                $borther2[] = $v['uid'];
            }

            array_push($borther2,$belong[0]['belong']);

            if($borther2){
                $in = [
                    'assign',$borther2
                ];
            }

        }

        $opt['status'] = ['!=','-1'];

        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $list = Position::getList($page_info['skip'],$page_info['limit'],$opt,$in);

        $count = Position::getCount($opt,$in);
       
        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        $user = Auth::user()->load('frame');

        if ($user->frame){

            $member = @Frame::getMember($user->frame->id);

        }else{
            
            $member = [];

        }

        $member[] = Auth::id();

        $in = ['assign'=>$member];

        $client = Client::getAll([],$in);

        return view('Home.User.Position.position_self',compact('client','list','page','num','act'));
    }

    public function all(Request $request)
    {
        $opt = [];
        $opt['state'] = 1;
        $act = [];

        if ( !empty($request->input('title')) ){

            $opt['title'] =['like','%'.$request->input('title').'%'] ;

        }
        if ( !empty($request->input('client_id')) ){

            $opt['client_id'] = $request->input('client_id');

        }

        $act['title'] =  $request->input('title')??'';

        $act['client_id'] =  $request->input('client_id')??'';

        $opt['status'] = ['!=','-1'];

        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $list = Position::getList($page_info['skip'],$page_info['limit'],$opt);
        
        $count = Position::getCount($opt);

        $user = Auth::user()->load('frame');

        $member = Frame::getMember($user->frame->id);

        $member[] = Auth::id();

        $in = ['assign'=>$member];

        $client = Client::getAll([],$in);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));

        return view('Home.User.Position.position_all',compact('list','page','num','client','act'));
    }

    public function add(Request $request){
        if($request->isMethod('post')){
            //验证
            $this->validate(request(), [
                'time' => 'nullable|string',
                'emergency' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'client_id' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'title' => 'required|string',
                'region' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'range' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                /*
                'category' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],*/
                'state' => 'required',
                'hc' => 'required|string',
                'reward' => 'nullable|string',
                'assign' => 'nullable|integer',
                'shareTo' => 'required|integer',
            ],[],[
                'time' => '招聘时间',
                'emergency' => '紧急程度',
                'title' => '职位名称',
                'region' => '工作地点',
                'range' => '薪资范围',
/*                'category' => '职位类别',*/
                'state' => '需求状态',
                'reward' => '悬赏金',
                'client_id' => '所属客户',
                'assign' => '归属',
                'shareTo' => '任务归属',
            ]);

            //数据库操作
            $data = [];
            foreach ($request->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    $data[$key] = $val;
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $data['assign'] = Auth::id();
                    $data['share'] = 0;
                    break;
                case 2:
                    $data['assign'] = '';
                    $data['share'] = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $data['assign'] = $assign;
                        $data['share'] = 0;
                    }else{
                        $data['assign'] = '';
                        $data['share'] = 1;
                    }
                    break;
                default:
                    $data['assign'] = '';
                    $data['share'] = 1;
            }

            $data['uid'] = Auth::id();
            $res = PositionModel::create($data);

            return ['code'=>1];
            //返回结果
        }

        $user = Auth::user()->load('frame');

        $member = Frame::getMember($user->frame->id);

        $member[] = Auth::id();

        $in = ['assign'=>$member];

        $client = Client::getAll([],$in);

        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        $position_class = PositionClass::getTreeList();

        $country = config('base.country');

        $working_salary = config('base.working_salary');

        return view('Home.User.Position.position_add',compact('client','frame','position_class','country','working_salary'));
    }

    public function edit(PositionModel $obj){
        if(request() ->isMethod('post')){
            //验证
            $rules = [
                'time' => 'nullable|string',
                'emergency' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'client_id' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'title' => 'required|string',
                'region' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
                'range' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],
/*                'category' => [function ($attribute, $value, $fail) {
                    if (!$value) {
                        $fail(':attribute 未选择。');
                    }
                }],*/
                'state' => 'required',
                'reward' => 'nullable|string',
                'hc' => 'required|string',
                'assign' => 'nullable|integer',
                'shareTo' => 'required|integer',
            ];

            if (($obj->share || $obj->assign == Auth::id()) && $obj->uid!=Auth::id() && !Auth::user()->hasRole('admin')){
                foreach ($rules as $k => $v){
                    if (!in_array($k,['shareTo','state'])){
                        unset($rules[$k]);
                    }
                }
            }

            $this->validate(request(), $rules,[],[
                'time' => '招聘时间',
                'emergency' => '紧急程度',
                'title' => '职位名称',
                'region' => '工作地点',
                'range' => '薪资范围',
/*                'category' => '职位类别',*/
                'state' => '需求状态',
                'reward' => '悬赏金',
                'client_id' => '所属客户',
                'assign' => '归属',
                'shareTo' => '任务归属',
            ]);

            //数据库操作
            foreach (request()->all() as $key => $val){
                if (!is_numeric($val)){	$val = clean($val);}
                if(in_array($key,$this->passField)){
                    $obj->$key = $val;
                }
            }

            switch (intval(request()->post('shareTo'))){
                case 1:
                    $obj->assign = Auth::id();
                    $obj->share = 0;
                    break;
                case 2:
                    $obj->assign = '';
                    $obj->share = 1;
                    break;
                case 3:
                    if ($assign = intval(request()->post('assign'))){
                        $obj->assign = $assign;
                        $obj->share = 0;
                    }else{
                        $obj->assign = '';
                        $obj->share = 1;
                    }
                    break;
                default:
                    $obj->assign = '';
                    $obj->share = 1;
            }

            $res = $obj->save();
            //返回结果
            return ['code'=>1];
        }

        $obj->load(['user','client']);

        $user = Auth::user()->load('frame');

        if (Auth::user()->type==1){

            $member = Frame::getMember($user->frame->id);

            $member[] = Auth::id();

            $in = ['assign'=>$member];

        }else{

            $in = ['assign'=>[Auth::id()]];

        }

        $client = Client::getAll([],$in);

        $frame = Frame::GetFrame(config('base.branch.lg.id'),config('base.level.admin'));

        if ($obj->assign){
            if ($obj->assign == Auth::id()){
                $obj->shareTo = 1;
            }else{
                $obj->shareTo = 3;
            }
        }else{
            $obj->shareTo = 2;
        }

        $position_class = PositionClass::getTreeList();

        $country = config('base.country');

        $working_salary = config('base.working_salary');

        return view('Home.User.Position.position_edit',compact('obj','client','frame','position_class','country','working_salary'));
    }

    public function position_push(PositionModel $obj){
        if(request() ->isMethod('post')){
            //验证
            $this->validate(request(), [
                'id_list' => 'required',
            ],[
                'required' => '必选'
            ],[
                'id_list' => '简历数据'
            ]);

            //数据库操作

            $id_list = request()->post('id_list');

            $data = [];
            
            foreach ($id_list as $k => $v){
                # 查询当前职位表的权限是否属于本人
                if(DB::table('resume')->where(['id'=>$v])->value('assign')!=Auth::id()){
                    continue; // 跳过推荐
                }
                $data[$k]['uid'] = Auth::id();
                $data[$k]['resume_id'] = $v;
                $data[$k]['status'] = 1;
            }

            $obj->deliver()->createMany($data);

            return ['code'=>1];
        }

        $opt = [];

        $in = [];

        if (!Auth::user()->hasRole('admin') && Auth::user()->type==1){

            $user = Auth::user()->load('frame');

            $member = Frame::getMember($user->frame->id);

            $member[] = Auth::id();

            $in = ['assign',$member];

            $opt['assign'] = Auth::id();

        }else{

            $in = ['uid',[Auth::id()]];

            if(!Auth::user()->hasRole('admin')){

                $opt['user_time'] = ['>',time()];

            }

        }


        # 如果上级是管理组就拥有上级和兄弟查看权限
        $belong  = json_decode(Db::table('frame')->where(['uid'=>Auth::id()])->get(),true);

        if(@$belong[0]['level']==3 && @$belong[0]['belong']!=0 ){

            $borther = json_decode(Db::table('frame')->where(['belong'=>$belong[0]['belong']])->select('uid')->get(),true);

            foreach($borther as $k=>$v){
                $borther2[] = $v['uid'];
            }

            array_push($borther2,$belong[0]['belong']);

            if($borther2){
                $in = [
                    'assign',$borther2
                ];
            }

        }

        $list = [];
        if ($obj->state){
            if ($obj->assign == in_array( Auth::id(),$in[1]) || Auth::user()->type!=1){
                if(Auth::user()->type==1){
                    $opt = [];
                }
                $list = Resume::getList(true,true,$opt,$in,true,true,false,true,$obj->id);
            }
        }
       
        return view('Home.User.Position.position_push',compact('list','obj'));
    }

    public function position_resume(PositionModel $obj,Request $request){

        $page = $request->input('page');

        $page_info = Tools::page_helper($page,config('base.home_limit.base_limit.render_limit'),config('base.home_limit.base_limit.limit'));

        $opt = ['position_id'=>$obj->id];

        if (Auth::user()->type!=1){

            $resume_opt = ['uid'=>Auth::id(),'user_time' => ['>',time()]];

        }else{

            $resume_opt = [];

        }

        $list = Deliver::getList($page_info['skip'],$page_info['limit'],$opt,'resume',$resume_opt);

        $count = Deliver::getCount($opt);

        $num = intval(ceil($count/config('base.home_limit.base_limit.limit')));
        
        return view('Home.User.Position.position_resume',compact('list','obj','page','num'));
    }
    /*删除职位*/
    public function position_del(PositionModel $obj){
        if(Auth::user()->hasAnyRole(['admin']) || Auth::id()==$obj->uid){

            $obj->status = '-1';

            $res = $obj->save();

            if ($res){

                $rerurn = ['code'=>1,'msg'=>'OK'];

            }else{

                $rerurn = ['code'=>0,'msg'=>'服务器错误'];
            }
        }else{

            $rerurn = ['code'=>0,'msg'=>'没有权限'];
        }

        return $rerurn;
    }

}